<!-- 发布、编辑博客页面 -->

<script setup lang="ts">
import { ref, shallowRef, onBeforeUnmount, nextTick, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' 

const router = useRouter()
const route = useRoute()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容
const valueHtml = ref('')

// 表单数据
const form = ref({
  title: '',
  category: '',
  cover: '',
  summary: '',
  content: '',
  topics: [] as string[]
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2-100个字符之间', trigger: 'blur' }
  ],
  category: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

// 分类
const categories = ref([
  {
    label: '论坛',
    value: 'forum'
  },
  {
    label: '新闻',
    value: 'news'
  }
])

// 话题
const topics = ref([
  {
    label: '科技',
    value: 'tech'
  },
  {
    label: '娱乐',
    value: 'entertainment'
  },
  {
    label: '体育',
    value: 'sports'
  },
  {
    label: '财经',
    value: 'finance'
  },
  {
    label: '教育',
    value: 'education'
  },
  {
    label: '健康',
    value: 'health'
  },
  {
    label: '时尚',
    value: 'fashion'
  },
  {
    label: '美食',
    value: 'food'
  }
])

// 话题输入相关
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref()

// 显示输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

// 处理输入确认
const handleInputConfirm = () => {
  if (inputValue.value) {
    form.value.topics.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 删除话题标签
const handleClose = (tag: string) => {
  form.value.topics = form.value.topics.filter((t: string) => t !== tag)
}

// 上传封面
const handleCoverSuccess = (response: any) => {
  form.value.cover = response.url
}

// 编辑器回调函数
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例
}

const formRef = ref()

// 保存文章
const handleSave = async () => {
  try {
    // 表单校验
    await formRef.value.validate()

    // 设置文章内容
    form.value.content = editorRef.value.getHtml()

    // TODO: 调用API保存文章
    ElMessage.success('保存成功')
    router.push('/news')
  } catch (error) {
    if (error === false) {
      ElMessage.warning('请完善文章信息')
      return
    }
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消编辑
const handleCancel = () => {
  router.back()
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 搜索建议
const querySearch = (queryString: string, cb: (arg: any[]) => void) => {
  const results = queryString
    ? topics.value.filter((topic: { label: string; value: string }) => {
        return topic.label.toLowerCase().includes(queryString.toLowerCase())
      })
    : topics.value
  cb(results)
}

// 选择建议
const handleSelect = (item: any) => {
  inputValue.value = item.label
  handleInputConfirm()
}

// 获取文章详情
const getArticleDetail = async (id: string, type: string) => {
  try {
    // 模拟后台返回的数据
    const mockData = {
      title: '人工智能发展最新动态',
      category: 'news',
      cover: 'https://picsum.photos/800/600',
      summary: '本文介绍了人工智能领域的最新发展动态和未来趋势...',
      content: '<p>人工智能技术正在快速发展,影响着我们生活的方方面面...</p>',
      topics: ['AI', '科技', '创新']
    }

    // 填充表单数据
    form.value = {
      title: mockData.title,
      category: mockData.category,
      cover: mockData.cover,
      summary: mockData.summary,
      content: mockData.content,
      topics: mockData.topics || []
    }

    // 设置编辑器内容
    valueHtml.value = mockData.content
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  }
}

// 组件挂载时检查是否有query参数
onMounted(() => {
  const { id, type } = route.query
  if (id && type) {
    getArticleDetail(id as string, type as string)
  }
})
</script>

<template>
  <div class="max-w-[1000px] mx-auto py-8 px-4">
    <div class="bg-white rounded-lg">
      <!-- 页面标题 -->
      <div class="p-6 border-b">
        <h1 class="text-2xl font-bold">
          {{ route.query.id ? '编辑文章' : '发布文章' }}
        </h1>
      </div>

      <!-- 表单内容 -->
      <div class="p-6">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="space-y-6"
        >
          <!-- 标题 -->
          <el-form-item
            label="文章标题"
            prop="title"
            required
          >
            <el-input
              v-model="form.title"
              placeholder="请输入文章标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <!-- 分类 -->
          <el-form-item
            label="所属分类"
            prop="category"
            required
          >
            <el-select
              v-model="form.category"
              placeholder="请选择分类"
            >
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- 话题 -->
          <el-form-item label="文章话题">
            <el-tag
              v-for="tag in form.topics"
              :key="tag"
              class="mx-1"
              closable
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-autocomplete
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="ml-1"
              style="width: 150px"
              size="small"
              :fetch-suggestions="querySearch"
              value-key="label"
              @select="handleSelect"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
              placeholder="输入话题"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput"
            >
              + 新话题
            </el-button>
          </el-form-item>

          <!-- 封面 -->
          <el-form-item label="文章封面">
            <div class="flex items-center gap-4">
              <el-upload
                class="cover-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
              >
                <div
                  v-if="form.cover"
                  class="w-[100px] h-[100px] border border-dashed border-gray-300 rounded-lg overflow-hidden"
                >
                  <img
                    :src="form.cover"
                    class="w-full h-full object-cover"
                  />
                </div>
                <div
                  v-else
                  class="w-[200px] h-[200px] border border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center cursor-pointer hover:border-primary"
                >
                  <el-icon class="text-3xl text-gray-400"><Plus /></el-icon>
                  <span class="mt-2 text-gray-500">上传封面</span>
                </div>
              </el-upload>
              <div class="text-gray-500 text-sm">
                建议尺寸：800x600px，支持 jpg、png 格式
              </div>
            </div>
          </el-form-item>

          <!-- 摘要 -->
          <el-form-item label="文章摘要">
            <el-input
              v-model="form.summary"
              type="textarea"
              :rows="3"
              placeholder="请输入文章摘要"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <!-- 内容 -->
          <el-form-item
            label="文章内容"
            prop="content"
            required
          >
            <div class="border rounded-lg">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="editorConfig"
                mode="default"
              />
              <Editor
                style="height: 500px"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div class="flex justify-end gap-4 mt-8">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            type="primary"
            @click="handleSave"
          >
            保存博客
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.cover-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.el-button--primary {
  --el-button-bg-color: #056de8;
  --el-button-border-color: #056de8;
  --el-button-hover-bg-color: #0461cf;
  --el-button-hover-border-color: #0461cf;
}
</style>
